import { useEffect, useState } from 'react';
import instance from "../pages/utils/https";
import {  useDispatch } from "react-redux";
import { setUserInfo } from "../store/modules/data";
import {  Toast } from 'react-vant';

const useWechatLogin = () => {
  const [isLoading, setIsLoading] = useState(false); // 加载状态
  const [isDialogVisible, setIsDialogVisible] = useState(false); // 弹框状态

  // 微信授权登录
  const handleWechatLogin = () => {
    const appId = 'wxc84327f9bba81aff'; // 替换为你的微信 AppID
    const redirectUri = encodeURIComponent('https://zcgjcy.com/app/layout/home'); // 替换为你的回调地址
    const scope = 'snsapi_userinfo' //'snsapi_userinfo'; // 授权范围
    // const state = 'STATE'; // 可选参数，用于防止 CSRF 攻击


    // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect

// scope为snsapi_userinfo：

// https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx807d86fb6b3d4fd2&redirect_uri=http%3A%2F%2Fdevelopers.weixin.qq.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    // 跳转到微信授权页面
    const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=123#wechat_redirect`;
    window.location.href = authUrl;
  };

  // 从 URL 中获取授权码（code）
  const getCodeFromUrl = () => {
    // alert(JSON.stringify(window.location))
    const query = new URLSearchParams(window.location.search);
    return query.get('code');
  };


  const dispatch = useDispatch();
  // 处理微信回调
  useEffect(() => {
    const code = getCodeFromUrl();
    if (code) {
      // 如果有 code，直接发送到后端获取用户信息
      setIsLoading(true);
      instance.get('/api/wechat-login', { params:{code} })
        .then((response) => {
          const userInfo = response.data;
          console.log('用户信息:', userInfo);
          Toast.success('登录成功！');
          // 在这里处理用户信息，比如存储到 Redux 或本地存储
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
          dispatch(setUserInfo(userInfo));
        })
        .catch((error) => {
          console.error('登录失败:', error);
          Toast.fail('登录失败，请重试！');
        })
        .finally(() => {
          setIsLoading(false);
        });
    } else {
      // 如果没有 code，弹出授权弹框
      setIsDialogVisible(true);
    }
  }, []);

  return {
    isDialogVisible,
    setIsDialogVisible,
    handleWechatLogin,
    isLoading,
  };
};

export default useWechatLogin;